package com.zdp.auth.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.zdp.auth.LoginBody;
import com.zdp.auth.LoginVo;
import com.zdp.auth.service.IAuthStrategy;
import com.zdp.auth.service.SysLoginService;
import com.zdp.entity.base.R;
import com.zdp.pojo.RemoteClientVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequiredArgsConstructor
public class TokenController {

    private final SysLoginService sysLoginService;


    /**
     * {"username":"zdp","password":"123456","grantType":"password","clientId":"e5cd7e4891bf95d1d19206ce24a7b32e","tenantId":"000000"}
     */
    @PostMapping("login")
    public R<LoginVo> login(@RequestBody LoginBody loginBody) {
        // 授权类型和客户端id
        String clientId = loginBody.getClientId();
        String grantType = loginBody.getGrantType();

        // RemoteClientVo clientVo = remoteClientService.queryByClientId(clientId);
        RemoteClientVo clientVo = new RemoteClientVo();
        clientVo.setGrantType("password");
        clientVo.setDeviceType("pc");
        clientVo.setTimeout(604800L);
        clientVo.setActiveTimeout(604800L);
        clientVo.setClientId(clientId);

        // 查询不到 client 或 client 内不包含 grantType
        if (ObjectUtil.isNull(clientVo) || !StringUtils.contains(clientVo.getGrantType(), grantType)) {
            log.info("客户端id: {} 认证类型：{} 异常!.", clientId, grantType);
            return R.fail("auth.grant.type.error");
        }
        // 校验租户信息
        // sysLoginService.checkTenant(loginBody.getTenantId());

        return R.ok(IAuthStrategy.login(loginBody, clientVo));
    }

    /**
     * 强制注销
     */
    @PostMapping("/logout")
    public R<Void> logout(@RequestParam("loginId")String loginId) {
        StpUtil.logout(loginId);
        return R.ok(null);
    }


    /**
     * 踢人下线
     */
    @PostMapping("/kickout")
    public R<Void> kickout(@RequestParam("loginId")String loginId) {
        StpUtil.kickout(loginId);
        return R.ok(null);
    }



    /**
     * 账号封禁
     */
    @PostMapping("/disable")
    public R<Void> disable(@RequestParam("loginId")String loginId) {
        // 先踢下线
        StpUtil.kickout(loginId);
        // 再封禁账号
        StpUtil.disable(loginId, 86400);
        return R.ok(null);
    }
}
